var qiniu = require('node-qiniu');
var config = require('../config/config.js')();
var debug = require('debug')('qiniu');
qiniu.config({
    access_key: config.qiniu.accessKey,
    secret_key: config.qiniu.secretKey
});
var myBucket = qiniu.bucket(config.qiniu.bucket);

var qiniuApi = {};
qiniuApi.addNew = function (name, path) {
    // return myBucket.putFile(name, path);
    return myBucket.putFile(name, path).then(function succ(reply) {
        debug('upload to qiniu succ', reply);
        var key = reply.key;
        key = config.qiniu.extUrlPrefix + key;
        return Promise.resolve(key);
    }, function fail(err) {
        debug('upload to qiniu err', err);
        return Promise.reject(err);
    });
}

qiniuApi.getUrlByKey = function (name) {
    var res = myBucket.key(name);
    var url = res.url();
    // var encodedUrl = res.entryUrl();
    return url;
}


module.exports = exports = qiniuApi;